package com.tul.exercise.base.java8.stream.methodrefrence;

import com.tul.exercise.base.java8.stream.base.Apple;
import com.tul.exercise.base.java8.stream.base.Artist;
import com.tul.exercise.base.java8.util.BeanCreator;
import com.tul.exercise.base.java8.util.BeanCreatorHelper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 方法引用
 *
 * @author tuliang
 */
public class MethodRefrenceTest {

    @Test
    @DisplayName("方法引用")
    public void test01() {
        Supplier<String> newStr = String::new;
        String str = newStr.get();
        System.out.println(str);

    }

    @Test
    @DisplayName("构造函数方法引用")
    public void test02() {

        // 无参构造函数的引用
        List<Apple> appleList = Stream.of("apple1", "apple2")
                .map(Apple::new)
                .collect(Collectors.toList());
        System.out.println(appleList);

        // 1个参数构造函数的引用
        Function<String, Apple> createApple = name -> new Apple(name);
        List<Apple> apples = Stream.of("apple1", "apple2")
                .map(createApple)
                .collect(Collectors.toList());
        System.out.println(apples);

        // 2个参数构造函数的引用
        BiFunction<String, Double, Apple> createApple2 = (name, weight) -> new Apple(name, weight);
        List<Apple> apples1 = Stream.of(new AppleBean("apple1", 23.9),
                new AppleBean("apple2", 34.9))
                .map(bean -> createApple2.apply(bean.getName(), bean.getWeight()))
                .collect(Collectors.toList());
        System.out.println(apples1);
    }

    /**
     * Apple的辅助类
     */
    public static class AppleBean {
        private String name;
        private double weight;
        private String color;

        public AppleBean(String name, double weight) {
            this.name = name;
            this.weight = weight;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public double getWeight() {
            return weight;
        }

        public void setWeight(double weight) {
            this.weight = weight;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }
}
